package com.youdianstar.app.adapter

import android.content.Context

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.youdianstar.app.R
import com.youdianstar.app.databinding.LayoutItemBranchBinding
import com.youdianstar.app.entity.BranchInfo
import com.youdianstar.app.ui.BranchDetailActivity
import com.youdianstar.app.util.MapJumpUtil
import com.youdianstar.app.common.ConfigKey
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.util.LatLngUtil


/**
 * File: BranchPagingAdapter
 * Author: 82149 Create: 2021/9/29 11:59
 * Changes (from 2021/9/29)
 * --------------------------------------------------
 * description: 网点列表: 使用 paging3 处理分页的方案, 没有继承BasePagingAdapter 的用法
 * ---------------------------------------------------
 *
 */
class BranchPagingAdapter(val context:Context) : PagingDataAdapter<BranchInfo, RecyclerView.ViewHolder>(differCallback) {
    companion object {
        val TAG  = "BranchPagingAdapter"
        val differCallback = object : DiffUtil.ItemCallback<BranchInfo>() {
            override fun areItemsTheSame(oldItem: BranchInfo, newItem: BranchInfo): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: BranchInfo, newItem: BranchInfo): Boolean {
                return oldItem == newItem
            }
        }
    }

    internal class BranchVH(val binding: LayoutItemBranchBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bindData(mContext:Context,data: BranchInfo) {
            // 只显示商家名称，不显示地址
            setText(binding.itemBranchName, data.branchName)
            setText(binding.tvAvailableNum, data.rent.toString())
            setText(binding.tvReturnNum, data.recovery.toString())

            // 联系电话
            if (!StrUtil.isEmpty(data.landlinePhone)) {
                binding.itemBranchPhone.visibility = View.VISIBLE
                binding.itemBranchPhone.text = data.landlinePhone
            } else {
                binding.itemBranchPhone.visibility = View.GONE
            }

            // 营业时间
            if (!StrUtil.isEmpty(data.openTime)) {
                binding.itemBranchOpenTime.visibility = View.VISIBLE
                binding.itemBranchOpenTime.text = data.openTime
            } else {
                binding.itemBranchOpenTime.visibility = View.GONE
            }

            val isOnline :Boolean = data.isBusiness
            binding.itemIvStatus.visibility = if (isOnline) View.INVISIBLE else View.VISIBLE
            binding.itemBranchName.setTextColor(getViewColor(mContext, if (isOnline) R.color.color_39404D else R.color.color_888888))
            binding.tvRentAvailable.visibility = if (isOnline) View.VISIBLE else View.GONE
            binding.tvReturnAvailable.visibility = if (isOnline) View.VISIBLE else View.GONE
            binding.tvAvailableNum.visibility = if (isOnline) View.VISIBLE else View.GONE
            binding.tvReturnNum.visibility = if (isOnline) View.VISIBLE else View.GONE
            binding.tvOutLine.visibility = if (isOnline) View.GONE else View.VISIBLE

            //Logo
            val host = DataAppManager.instance.getConfig(ConfigKey.FILE_HOST)
            val logoUrl = host+data.logo
            val logoDF = R.mipmap.icon_default_logo
            if (StrUtil.isEmpty(data.logo)){
                setLocalGlide(binding.itemIvLogo,logoDF,logoDF)
            } else {
                setImgGlide(binding.itemIvLogo,logoUrl,logoDF)
            }
            //设置距离
            val localLocation = DataAppManager.instance.getLocalLatLng()
            val distanceStr = LatLngUtil.getDistanceMiTx(data.lat, data.lng, localLocation.latitude, localLocation.longitude)
            setText(binding.tvDistant, distanceStr)

            //binding.itemIvMap.setImageResource(if (isOnline) R.mipmap.icon_nav_open else R.mipmap.icon_nav_closed)
            binding.itemIvMap.setThrottleListener {
                LogUtil.i(TAG,"-----click item map")
                //传入经纬度,跳转谷歌地图
                val addressTx :String = if (!StrUtil.isEmpty(data.addressMap)) data.addressMap?:"" else data.address
                if (!StrUtil.isEmpty(addressTx)){
                    MapJumpUtil.jumpToGoogleMap(binding.root.context, addressTx)
                }
            }
        }

        private fun setText(view: TextView, text: String) {
            view.text = text
        }

        /**
         * Coil加载图片
         * @param url 网点logo url
         */
        private fun setImgGlide(imageView: ImageView, url: String, icDf:Int) {
            imageView.load(url) {
                error(icDf)
                placeholder(icDf)
            }
        }

        private fun setLocalGlide(imageView: ImageView,drawId:Int,icDf:Int){
            imageView.load(drawId) {
                //transformations(RoundedCornersTransformation(topLeft = 5f, topRight = 5f,bottomLeft = 5f, bottomRight = 5f))
                error(icDf)
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        getItem(position)?.let {
            (holder as BranchVH).bindData(context,it)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val branchItem = BranchVH(LayoutItemBranchBinding.inflate(LayoutInflater.from(parent.context), parent, false))
        branchItem.itemView.setOnClickListener {
            //跳转详情
            val data = getItem(branchItem.layoutPosition)
            data?.let { branch ->
                // 传递siteId和distance参数
                context.startActivity<BranchDetailActivity>(
                    Extra.IT_ID to branch.id,
                    Extra.IT_DISTANCE to branch.distance
                )
            }
        }
        return branchItem
    }


}